package com.example.hello.controller;


import com.example.hello.controller.request.ModifyDrinkRequest;
import com.example.hello.controller.request.ModifyStudentRequest;
import com.example.hello.model.Student;
import com.example.hello.repository.StudentRepository;
import com.example.hello.service.IStudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/student")
//处理/stu
public class StudentController {

    @Autowired
    private IStudentService studentService;
    //1.查询所有
    @GetMapping("/all")
    public List<Student> getAll(){

        List<Student> addList=studentService.getAllStudent();
        return addList;
    }

    //2.新增学生
    @PostMapping("/add")
    public Student addStudent(@RequestBody @Valid Student student, BindingResult bindingResult){
        log.info("创建新的:{}",student);
        if (bindingResult.hasErrors()) {
            for (ObjectError error:bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;
        } else {
            log.info("创建新学生:{}", student);
            studentService.addStudent(student);
            return student;
        }
    }

    //3.删除学生
    @DeleteMapping("/del/{id}")
    public String deletStudent(@PathVariable Long id){
        log.info("删除:{}",id,"成功");
        studentService.deleteStudent(id);
        return "删除操作成功";
    }


    //4.查询学生
    @GetMapping("/{id}")
    public Student serchStudent(@PathVariable Long id){
        Student student=Student.builder().id(Long.valueOf(7)).name("zhhx").adminssionDate(LocalDate.parse("2020-10-14")).major("移开").build();
        return student;
    }

    //5.修改学生信息
    @PutMapping("/update")
    public Student modifyStudent(@RequestBody ModifyStudentRequest modifyStudentRequest){
        log.info("要修改的学生:{}",modifyStudentRequest);
        //request是另外一个新的学生模型，通过id把需要修改的学生模型暂存在这个模型里面
        Student student =studentService.getStudentById(modifyStudentRequest.getId());
        //通过BeanUtils用暂时存储的新request模型把数据库里面的老数据替代了 id是同样的id 数据是新的数据
        BeanUtils.copyProperties(modifyStudentRequest,student);
        //最后把这个更新过后的数据再存进去 实现修改功能
        studentService.updateStudent(student);
        return student;
    }

    @PostMapping(value = "/listupload",consumes = (MediaType.MULTIPART_FORM_DATA_VALUE))
    public List<Student> listuploadFile(MultipartFile file){
        List<Student> result=new ArrayList<>();
        try {
            BufferedReader reader=new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line="";
            //每次循环都读取一行，不为空就继续往下读
            while ((line=reader.readLine())!=null){
                String[] args=line.split(",");
                Student student=Student.builder().id(Long.parseLong(args[0])).name(args[1]).adminssionDate(LocalDate.parse(args[2])).major(args[3]).build();
                result.add(student);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}
